﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Messaging;
using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;

namespace SampleApp.Services
{
	public class NotificationService
	{
		const string toastRegistrationName = "SampleAppRegistration";
		const string tileRegistrationName = "SampleAppTileregistration";
		NotificationHub hub;

		public Task Initialize()
		{
			var connectionString = ConnectionString.CreateUsingSharedAccessSecretWithListenAccess( "ENDPOINT" , "LISTEN ACCESS SECRET" );

			hub = new NotificationHub( "sampleapp", connectionString );

			return Task.Run( () =>
			{
				this.InitNotifications();
			} );
		}

		private async void InitNotifications()
		{
			await hub.RefreshRegistrationsAsync();

			if ( !await hub.RegistrationExistsForApplicationAsync( toastRegistrationName ) )
			{
				var template = ToastNotificationManager.GetTemplateContent( ToastTemplateType.ToastText01 );
				var textNode = template.SelectSingleNode( "//text[@id='1']" ) as XmlElement;
				if ( textNode != null )
				{
					textNode.InnerText = "$(property1)";
				}

				var toastNode = template.SelectSingleNode( "toast" );
				( ( XmlElement )toastNode ).SetAttribute( "launch", "SampleApp-sample-context" );

				await hub.CreateTemplateRegistrationForApplicationAsync( template, toastRegistrationName, new string[] { "my-tag" } );
			}

			if ( !await hub.RegistrationExistsForApplicationAsync( tileRegistrationName ) )
			{
				await hub.CreateRegistrationForApplicationAsync( tileRegistrationName, new string[] { "my-tag" } );
			}
		}
	}
}
